package com.yanq.liancar.activity;
/*
 *  @创建者     Administrator
 *  @创建时间   2018/11/29  14:16
 *  @描述       ${TODO}
 */


import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.ShopListAdapter;
import com.yanq.liancar.bean.ShopListBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.GlideImageLoader;
import com.yanq.liancar.util.LogUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SmallCDelicateShopActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right2)
    ImageView ivRight2;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.common_toolbar)
    Toolbar commonToolbar;
    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_noshop)
    LinearLayout llNoshop;
    private List<ShopListBean.DataBean> shopListBeanList = new ArrayList<>();
    private ShopListAdapter adapter;
    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    private double Latitude, Longitude;
    private List<Integer> imageUrl;
    private int page = 1;
    private boolean isClear = true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smallc_delicateshop);
        mTvTitle.setText("店铺列表");
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        ButterKnife.bind(this);

        initBannerData();
        getLocation();
        initRecyclerView();
        refreshListener();      //下拉刷新
    }

    private void initRecyclerView() {
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new ShopListAdapter(R.layout.item_fuwu, shopListBeanList);
        recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("shopId", shopListBeanList.get(position).getId());
                LogUtils.e("shopId", shopListBeanList.get(position).getId() + "");
                RxActivityTool.skipActivity(mContext, ShopDetailsActivity.class, bundle);
            }
        });
    }

    private void refreshListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                isClear = true;

                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isClear = false;
                page++;

                refreshLayout.finishLoadMore();
            }
        });
    }

    private void initBannerData() {
        imageUrl = new ArrayList<>();
        imageUrl.add(R.mipmap.banner1);
        imageUrl.add(R.mipmap.banner2);
        imageUrl.add(R.mipmap.banner3);
        imageUrl.add(R.mipmap.banner4);
        imageUrl.add(R.mipmap.banner5);
        imageUrl.add(R.mipmap.banner6);
        banner.setImageLoader(new GlideImageLoader())
                .setImages(imageUrl)//设置图片集合
                .setDelayTime(3000)//设置轮播时间
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)//设置指示器位置（当banner模式中有指示器时）
                .setIndicatorGravity(BannerConfig.CENTER)
                .start();//banner设置方法全部调用完毕时最后调用
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                //ToastUtils.showToast(SmallBGoodsDetailsActivity.this, "您点击了第" + (mBanners.get(position).type + 1) + "张照片");
            }
        });
    }

    private void getLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        //        /**
        //         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
        //         */
        //        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        //        if(null != mLocationClient){
        //            mLocationClient.setLocationOption(mLocationOption);
        //            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        //            mLocationClient.stopLocation();
        //            mLocationClient.startLocation();
        //        }

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        Latitude = aMapLocation.getLatitude();//获取纬度
                        Longitude = aMapLocation.getLongitude();//获取经度
                        LogUtils.e("经纬度====", Latitude + "=======" + Longitude);
                        getShopByLang();
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    //根据距离查询店铺
    private void getShopByLang() {
        OkGo.<String>post(Config.s + "llc/shop/queryShopByLang")
                .tag(this)
                .params("lang", 1000)
                .params("lat", Latitude)
                .params("lon", Longitude)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ShopListBean baseBean = gson.fromJson(response.body(), ShopListBean.class);
                        if (baseBean.isIsSuccess()) {
                            shopListBeanList.clear();
                            shopListBeanList.addAll(baseBean.getData());
                            if (shopListBeanList.size() < 1) {
                                llNoshop.setVisibility(View.VISIBLE);
                            } else {
                                llNoshop.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }
}
